<template>
	<view class="container">
		<!-- 主内容 -->
		<view class="content">
			<view><button @click="goToGroup">管理组员</button></view>
			<!-- 组信息卡片 -->
			<view class="grid-container">
				<!-- 循环渲染组数据 -->
				<view class="group-card" :class="{'blue': index === 0, 'green': index === 1, 'purple': index >= 2}"
					v-for="(item, index) in groupList" :key="item.orgId">
					<view class="group-info">
						<text class="group-name">{{ item.orgName }}</text>
						<text class="group-leader">组长: {{ item.userName }}</text>
						<text class="group-points">组长可分配积分: {{ item.points }}</text>
					</view>

					<view class="points-operation">
						<input type="number" placeholder="分配积分" class="points-input" v-model="item.assignPoints" />
						<button class="assign-btn" @click="handleAssign(item)">分配</button>
					</view>
				</view>
			</view>

			<view class="add-member-section">
			  <text class="section-title">添加组长</text>
			  <view class="add-member-form">
			   
			    <button class="add-btn" @click="addGroup">添加组长</button>
			  </view>
			</view>
			<!-- 积分图表 -->
			<!-- <view class="chart-container">
				<text class="chart-title">各组积分概览</text>
				<view class="chart-placeholder">
					<text class="chart-loading">积分图表区域（后续对接后端数据）</text>
				</view>
			</view> -->
		</view>
	</view>
	 <view class="dialog-mask" v-if="showUserDialog">
	        <view class="dialog-container">
	            <view class="dialog-header">
	                <text class="dialog-title">选择组长（可多选）</text>
	                <text class="dialog-close" @click="showUserDialog = false">×</text>
	            </view>
	            
	            <view class="dialog-body">
	                <view 
	                    class="user-item" 
	                    v-for="user in userList" 
	                    :key="user.userId"
	                    :class="{ 'selected': selectedUserIds.includes(user.userId) }"
	                    @click="toggleUserSelection(user.userId)"
	                >
	                    <view class="user-info">
	                        <text class="user-name">{{ user.nickName || user.userName }}</text>
	                        <text class="user-id">ID: {{ user.userId }}</text>
	                    </view>
	                    <!-- 多选状态图标 -->
	                    <view class="user-check" v-if="selectedUserIds.includes(user.userId)">✓</view>
	                </view>
	                
	                <view class="empty-tip" v-if="userList.length === 0">
	                    暂无用户数据
	                </view>
	            </view>
	            
	            <view class="dialog-footer">
	                <view class="selected-count" v-if="selectedUserIds.length > 0">
	                    已选择: {{ selectedUserIds.length }}人
	                </view>
	                <button class="cancel-btn" @click="showUserDialog = false">取消</button>
	                <button class="confirm-btn" @click="confirmAddUsers" :disabled="selectedUserIds.length === 0">
	                    确认添加
	                </button>
	            </view>
	        </view>
	    </view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		http
	} from '../../../../utils/requestUtil';
	const orgId = ref()
	// 存储组列表数据（包含接口返回数据和临时分配的积分）
	const groupList = ref([])
	const goToGroup = ()=>{
		uni.navigateTo({
			url:"/pages/integration/intergrationMark/groupManage/groupManage?orgId="+orgId.value
		})
	}
	
	// const addGroup =async ()=>{
	// 	const res = await http.get("/system/role/authUser/allocatedList?pageNum=1&pageSize=1000&roleId=101")
	// 	console.log(res)
	// }
	// 加载数据的方法
	const loadData = async (id) => {
		try {
			const res = await http.get(`/integral/organization/getByParentAngGroupId?parentId=${id}`)
			if (res.code === 200 && res.data) {
				// 给每个组添加一个临时的assignPoints属性（用于输入框双向绑定）
				groupList.value = res.data.map(item => ({
					...item,
					assignPoints: '' // 初始为空
				}))
			} else {
				console.error('数据加载失败:', res.msg)
			}
		} catch (error) {
			console.error('请求异常:', error)
		}
	}
	// 新增：弹框相关变量
		// 修改：使用数组存储多个选中的用户ID
		    const showUserDialog = ref(false)
		    const userList = ref([])
		    const selectedUserIds = ref([]) // 改为数组
		// 新增：打开弹框时加载用户数据
		
		    const addGroup = async () => {
		        try {
		            const res = await http.get("/system/role/authUser/allocatedList?pageNum=1&pageSize=1000&roleId=101")
		            if (res.code === 200 && res.rows) {
		              // 获取当前已存在的userId列表
		                          const existingUserIds = groupList.value.map(item => item.userId)
		                          
								  existingUserIds.push(uni.getStorageSync("userId"))
		                          // 过滤掉已存在的用户
		                          userList.value = res.rows.filter(user => 
		                              !existingUserIds.includes(user.userId)
		                          )
								
		                showUserDialog.value = true
		                selectedUserIds.value = [] // 重置选中状态
		            } else {
		                uni.showToast({ title: '用户数据加载失败', icon: 'none' })
		            }
		        } catch (error) {
		            console.error('加载用户失败:', error)
		            uni.showToast({ title: '网络异常', icon: 'none' })
		        }
		    }
		
		    // 修改：切换用户选中状态（多选逻辑）
		    const toggleUserSelection = (userId) => {
		        const index = selectedUserIds.value.indexOf(userId)
		        if (index > -1) {
		            // 已选中，取消选择
		            selectedUserIds.value.splice(index, 1)
		        } else {
		            // 未选中，添加选择
		            selectedUserIds.value.push(userId)
		        }
		    }
		
		  const confirmAddUsers = async () => {
		      if (selectedUserIds.value.length === 0) {
		          uni.showToast({ title: '请至少选择一个用户', icon: 'none' })
		          return
		      }
		      
		      try {
		          // 调用后端批量添加接口
		          const res = await http.post(
		              `/integral/organization/batchAddLeaders?orgId=${orgId.value}`, 
		              selectedUserIds.value // 发送选中的用户ID列表
		          )
		          
		          if (res.code === 200) {
		              uni.showToast({ 
		                  title: `成功添加${selectedUserIds.value.length}位组长`, 
		                  icon: 'success' 
		              })
		              showUserDialog.value = false // 关闭弹框
		              loadData(orgId.value) // 刷新组列表
		          } else {
		              uni.showToast({ title: res.msg || '添加失败', icon: 'none' })
		          }
		      } catch (error) {
		          console.error('批量添加失败:', error)
		          uni.showToast({ title: '网络异常', icon: 'none' })
		      }
		  }


	// 分配积分的方法
	const handleAssign = async(item) => {
		if (!item.assignPoints || isNaN(item.assignPoints) || item.assignPoints <= 0) {
			uni.showToast({
				title: '请输入有效的积分',
				icon: 'none'
			})
			return
		}
		
		console.log(JSON.stringify(item)+uni.getStorageSync("userId"));
		// return
		// 这里可以调用分配积分的接口

// 正确写法：将 $ 改为 &，修正参数名
const res = await http.post(`/integral/organization/distrubutePointsByOgId?userId=${uni.getStorageSync("userId")}&orgId=${orgId.value}&points=${item.assignPoints}&bOrgId=${item.orgId}`)
console.log(res)
		if (res.code === 200) {
			uni.showToast({
				title: '分配成功',
				icon: 'success'
			})
			loadData(orgId.value)
			// 给每个组添加一个临时的assignPoints属性（用于输入框双向绑定）
			// groupList.value = res.data.map(item => ({
			// 	...item,
			// 	assignPoints: '' // 初始为空
			// }))
		} else {
			console.error('数据加载失败:', res.msg)
		}
		return
		
		
	}

	// 页面加载时触发
	onLoad((options) => {
		console.log('接收的参数:', options)
		if (options.orgId) {
			orgId.value = options.orgId
			loadData(options.orgId) // 传入parentId加载对应的数据
		} else {
			uni.showToast({
				title: '缺少参数orgId',
				icon: 'none'
			})
		}
	})
</script>

<style scoped>
	/* 原有样式保持不变 */
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.content {
		padding: 30rpx;
	}

	.grid-container {
		display: grid;
		grid-template-columns: 1fr;
		gap: 24rpx;
		margin-bottom: 40rpx;
	}

	@media (min-width: 768px) {
		.grid-container {
			grid-template-columns: repeat(3, 1fr);
		}
	}

	.group-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		border-left: 8rpx solid;
	}

	.blue {
		border-color: #4285f4;
	}

	.green {
		border-color: #34a853;
	}

	.purple {
		border-color: #9c27b0;
	}

	.group-name {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		display: block;
		margin-bottom: 15rpx;
	}

	.group-leader, .group-points {
		font-size: 28rpx;
		color: #666666;
		display: block;
		margin-bottom: 10rpx;
	}

	.points-operation {
		display: flex;
		align-items: center;
		gap: 16rpx;
		margin-top: 20rpx;
	}

	.points-input {
		flex: 1;
		height: 70rpx;
		border: 2rpx solid #dddddd;
		border-radius: 8rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}

	.assign-btn {
		background-color: #4e5fff;
		color: #ffffff;
		border: none;
		border-radius: 8rpx;
		padding: 0 30rpx;
		height: 70rpx;
		font-size: 28rpx;
	}

	.add-member-section {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		margin-bottom: 40rpx;
	}

	.add-member-form {
		display: flex;
		gap: 16rpx;
	}

	.add-btn {
		background-color: #34a853;
		color: #ffffff;
		border: none;
		border-radius: 8rpx;
		padding: 0 30rpx;
		height: 70rpx;
		font-size: 28rpx;
	}

	.chart-container {
		background-color: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.chart-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
		display: block;
	}

	.chart-placeholder {
		width: 100%;
		height: 400rpx;
		background-color: #f9f9f9;
		border-radius: 8rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.chart-loading {
		font-size: 28rpx;
		color: #999999;
	}

	/* 新增：弹框样式 */
	.dialog-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
		padding: 30rpx;
	}

	.dialog-container {
		width: 100%;
		max-width: 600rpx;
		background-color: #ffffff;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.dialog-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #eeeeee;
	}

	.dialog-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}

	.dialog-close {
		font-size: 40rpx;
		color: #999999;
		cursor: pointer;
	}

	.dialog-body {
		max-height: 600rpx;
		overflow-y: auto;
		padding: 20rpx;
	}

	.user-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 10rpx;
		background-color: #f9f9f9;
		cursor: pointer;
	}

	.user-item.selected {
		background-color: #e6f7ff;
		border: 1rpx solid #91d5ff;
	}

	.user-name {
		font-size: 28rpx;
		color: #333333;
	}

	.user-id {
		font-size: 24rpx;
		color: #666666;
		margin-top: 5rpx;
	}

	.user-check {
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		background-color: #4e5fff;
		color: white;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
	}

	.empty-tip {
		text-align: center;
		padding: 50rpx 0;
		color: #999999;
		font-size: 28rpx;
	}

	.dialog-footer {
		display: flex;
		border-top: 1rpx solid #eeeeee;
	}

	.cancel-btn, .confirm-btn {
		flex: 1;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		font-size: 28rpx;
		border: none;
		background-color: transparent;
	}

	.cancel-btn {
		color: #666666;
		border-right: 1rpx solid #eeeeee;
	}

	.confirm-btn {
		color: #4e5fff;
		font-weight: bold;
	}
</style>